package com.hycc.base;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueDemo {
    public static void main(String[] args) {
        test4();
    }

    /*
    * 抛出异常
    * */
    public static void test1(){
        ArrayBlockingQueue<Object> abq = new ArrayBlockingQueue<>(3);

        System.out.println(abq.add("a")); //true
        System.out.println(abq.add("b")); //true
        System.out.println(abq.add("c")); //true

        //IllegalStateException Queue full
        //System.out.println(abq.add("d"));

        System.out.println(abq.remove()); //a
        System.out.println(abq.remove()); //b
        System.out.println(abq.remove()); //c
        //NoSuchElementException
        //System.out.println(abq.remove());
    }

    /*
     * 不抛出异常
     * */
    public static void test2(){
        ArrayBlockingQueue<Object> abq = new ArrayBlockingQueue<>(3);

        System.out.println(abq.offer("a")); //true
        System.out.println(abq.offer("b")); //true
        System.out.println(abq.offer("c")); //true
        System.out.println(abq.offer("d")); //false

        System.out.println(abq.poll()); //a
        System.out.println(abq.poll()); //b
        System.out.println(abq.poll()); //c
        System.out.println(abq.poll()); //null
    }

    /*
     * 等待，阻塞 一直阻塞
     * */
    public static void test3() {
        ArrayBlockingQueue<Object> abq = new ArrayBlockingQueue<>(3);

        try {
            abq.put("a");
            abq.put("b");
            abq.put("c");
            //abq.put("d"); //队列满了，会一直阻塞
            System.out.println("put over");

            System.out.println(abq.take()); //a
            System.out.println(abq.take()); //b
            System.out.println(abq.take()); //c
            System.out.println(abq.take()); //队列空了，会一直阻塞

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    /*
     * 超时退出
     * */
    public static void test4(){
        ArrayBlockingQueue<Object> abq = new ArrayBlockingQueue<>(3);

        System.out.println(abq.offer("a")); //true
        System.out.println(abq.offer("b")); //true
        System.out.println(abq.offer("c")); //true
        try {
            System.out.println(abq.offer("d",2,TimeUnit.SECONDS)); //false
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(abq.poll()); //a
        System.out.println(abq.poll()); //b
        System.out.println(abq.poll()); //c
        try {
            System.out.println(abq.poll(2,TimeUnit.SECONDS)); //null
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
